<template>
  <div class="container">
    <div class="header">
      <span>消息({{ chatList.length }}) <sub @click="deleteChart" style="font-size:10px;font-weight: 600;color:#777;">清除所有</sub> </span>
    </div>
    <div class="chatBody">
      <div v-for="(item) in chatList" :key="item.id" class="chartName" @click="toChatList(item)" style="height: 70px">
        <div style="width: 70px" class="logoImage">
          <img style="width: 100%;height: 100%" :src="item.sheImg" alt="">
        </div>
        <div class="chartRight">
          <div class="chartNickName">
            {{ item.nickName }}
          </div>
          <div class="lastChart">
            {{ item.chat[item.chat.length - 1].content }}
          </div>
          <div :class="{dot:item.messageState }"></div>
        </div>

      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'Chart',
  data() {
    return {
      chatList: [],
      text: "",
      socketUrl: "ws://" + this.$ws + ":8887?userId=", // socket服务地址
      client: null, // webSocket实例
      myId: localStorage.getItem('user_id'),
      sheImg: localStorage.getItem('userimage'),
      data: "",
      sheNickName: localStorage.getItem('nickname'),
    }
  },
  created() {
    this.chatList = JSON.parse(localStorage.getItem('chatallinfo'))  //获取聊天记录生成列表
    if (!this.chatList) {
      this.chatList = []
      localStorage.setItem('chatallinfo', JSON.stringify([]))
    }
    this.initChaing()  //初始化ws连接
  },
  beforeDestroy() {
    this.client.close()     //组件销毁前关闭ws连接
    localStorage.setItem('chatallinfo', JSON.stringify(this.chatList))
  },
  methods: {
    deleteChart() {
      this.chatList = []
      localStorage.setItem('chatallinfo', JSON.stringify([]))
    },
    initChaing() {
      let that = this;
      if (window.WebSocket) {
        /* webSocket 连接服务器 */
        this.client = new WebSocket(this.socketUrl + this.myId);                     //这里要改为id

        /* 监听客户端连接 */
        this.client.onopen = function (ev) {
          if (ev.type === "open") {
            console.log("客户端连接socket服务");
          }
        };

        /* 监听服务端发送的消息 */
        this.client.onmessage = function (ev) {

          let data = JSON.parse(ev.data);
          let localRecord = that.chatList.some((item, idx) => {  //这里的this有问题
            if (item.id == data.myId) {
              that.chatList[idx].chat.push({myself: false, time: '', content: data.message})
              that.chatList[idx].messageState = true
              return true
            }
          })

          if (localRecord == false) {   //如果本地没有聊天记录,根据id获取用户信息创建聊天
            that.$http.post('/users/getInfo', {sheId: data.myId}).then((res) => {
              let result = res.data.sheInfo
              let ChartInfoMiddle = {
                id: result.id,
                sheName: result.username,
                nickName: result.nickname,
                messageState: true,
                sheImg: that.$baseUrl + result.userImage,
                chat: [{myself: false, time: '', content: data.message}]
              }
              that.chatList.push(ChartInfoMiddle)  //创造此聊天
            })
          }


        };

        /* 监听服务端关闭 */
        this.client.onclose = function () {
          console.log("socket服务已关闭");
          that.client = null; // 客户端或者是服务端断开后，将webSocket实例清除
        };

        /* 监听服务端异常 */
        this.client.onerror = function () {
          if (!that.client) {
            console.log("socket服务连接失败");
          }
        };
      } else {
        alert("该浏览器不支持webSocket，请使用主流浏览器，如chrome");
      }
    },
    sendData() {     //通过ws发送信息
      let data = {
        myId: this.myId,
        sheImg: this.sheImg,
        sheNickName: this.sheNickName,
        uid: new Date().getTime(),
        message: this.text,
        date: new Date(),
      };
      this.client.send(JSON.stringify(data));
      this.text = "";
    },
    toChatList(val) {
      localStorage.setItem('chatallinfo', JSON.stringify(this.chatList))
      this.$router.push({
        path: `/Chart/chatList/${val.id}`
      })
    }
  }
}
</script>
<style lang='less' scoped>
@import "../assets/style/theme";

.container {
  .header {
    text-align: center;
    height: 50px;
    line-height: 50px;
    background-color: @theme;
    font-size: 20px;
  }

  .chatBody {
    .chartName {
      display: flex;
      flex-direction: row;
      margin: 10px 0;

      .logoImage {
        margin-left: 10px;
        border-radius: 50%;
        overflow: hidden;
      }
    }

    .chartRight {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 100%;
      position: relative;

      .chartNickName {
        text-align: left;
        text-indent: 25px;
        height: 45px;
        line-height: 45px;
        font-weight: bold;
      }

      .lastChart {
        flex: 1;
        text-indent: 25px;

      }

      .dot {
        position: absolute;
        width: 10px;
        height: 10px;
        background-color: red;
        border-radius: 50%;
        top: 50%;
        transform: translateY(-50%);
        right: 20px;
      }
    }
  }
}
</style>
